package com.shuimin.group;

import com.shuimin.group.constant.GroupStatus;
import com.shuimin.group.mid.redis.RedisKey;
import com.shuimin.group.mid.redis.RedisService;
import com.shuimin.group.mid.redis.RedisUtil;
import com.shuimin.group.model.group.Group;
import com.shuimin.group.model.group.GroupMember;
import com.shuimin.group.model.group.VGroup;
import com.shuimin.group.model.group.VGroupMember;
import com.shuimin.group.model.weixin.WeixinUser;
import com.shuimin.group.service.GroupService;
import pond.common.S;
import pond.common.STRING;
import pond.db.Record;
import pond.web.Render;
import pond.web.Router;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class INNER_GROUP extends Router {
    {
        get("/", (req, resp) -> {
            String id = req.param("id");
            S.echo("id:"+id);
            if (STRING.isBlank(id)) {
                Map<String, Object> params = new HashMap<>();
                List<Map<String, Object>> ret = GroupService.allGroup("", params);
                resp.render(Render.json(ret));
            }
            else {
                resp.render(Render.json(GroupService.getGroupById(id)));
            }
        });
        /* 组个局 */
        post("/", (req, resp) -> {
            String userId = req.param("user_id");
            Group group = (Group) Record.newEntity(Group.class).merge(req.toMap());
            group.setId(S.uuid.vid());
            group.set("user_id",userId);
            if (group.get("book_time") == null || "nan".equals(group.get("book_time").toString().toLowerCase()))
            {
                resp.send(400, "book_time is" + group.get("book_time"));
                return;
            }
            long book_time =  new Long(group.get("book_time"));

            if (book_time < S.now() || (book_time - S.now() > (2*60*60*1000) ))
            {
                resp.send(400, "book_time ("+book_time+") not permit, (set < 2 hours)" );
                return;
            }

            //时间不能等于"NaN"
            if (group.get("create_time") == null || "nan".equals(group.get("create_time").toString().toLowerCase()))
            {
                group.set("create_time", new Date().getTime());
            }

            if (group.get("group_status") == null)
            {
                group.set("group_status", GroupStatus.GROUP_STATUS_CREATE.val());
            }

            GroupMember groupMember = new GroupMember();
            groupMember.setId(S.uuid.vid());
            groupMember.set("group_id",group.id());
            groupMember.set("user_id", userId);
            groupMember.set("is_creator", "1");
            groupMember.set("op_status", String.valueOf(1));
            groupMember.set("op_time", String.valueOf(S.now()));
            App.DB.post(t -> {
                t.recordInsert(group);
                t.recordInsert(groupMember);
            });
            VGroup vGroup = App.DB.get(t -> t.recordById(VGroup.class, group.id()));
            WeixinUser weixinUser = App.DB.get(t -> t.recordById(WeixinUser.class, userId));
            VGroupMember vGroupMember = new VGroupMember();
            vGroupMember.merge(groupMember.toMap());
            vGroupMember.merge(weixinUser.toMap());
            Map<String,Map<String,String>> map = new HashMap<>();
            map.put(RedisService.getGroupKey(vGroup), vGroup.toJedisMap());
            map.put(RedisService.getMemberKey(group.id(), userId), RedisService.getMemberValue(vGroupMember));
            S.echo(map);
            if (!RedisUtil.hAdd(map))
            {
                resp.send(400, " add failed");
                return;
            }
            resp.status(200);
            resp.render(Render.json(group));
        });

        del("/:id", (req, resp) -> {

            String groupId = req.param("id");
            String userId = App.getUserId(req);
            String key = RedisService.getGroupKeyById(groupId);
            if (STRING.isBlank(key))
            {
                resp.send(404,groupId + " not found");
                return;
            }
            Map<String, Object> vGroupMap = RedisUtil.hscanObjectsFromKey(key);
            List<String> keyList = RedisUtil.keys(groupId+"*"+ RedisKey.MEMBER);
            //添加局的key，取消，一起删除
            keyList.add(key);
            if (! RedisUtil.delKeys(keyList))
            {
                resp.send(400,"cancel failed" );
                return;
            }
            VGroup vGroup = new VGroup();
            vGroup.merge(vGroupMap);
            com.shuimin.group.model.group.Group group = vGroup.group();
            group.set("group_status", GroupStatus.GROUP_STATUS_MANUAL_CANCEL.val());
            App.DB.post(t->{
                t.recordUpdate(group);
            });
            resp.send(200, "ok");
        });
    }
}
